package tcc.wa.service;

import java.io.IOException;
import java.util.List;

import tcc.wa.model.GeographicCoordinate;
import tcc.wa.persistence.dao.LocationDAO;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationListener;
import android.location.LocationManager;
import android.util.Log;

/**
 * Service class for Location management.
 */
public class LocationService {

	private final String TAG = "LocationService";
	
	private final Context context;
	
	private final LocationDAO locationDAO;

	public LocationService(Context context) {
		this.context = context;
		locationDAO = new LocationDAO(context);
	}
	
	/**
	 * Updates device location.
	 *
	 * @param locationListener the location listener
	 */
	public void updateLocation(LocationListener locationListener) {
		Log.i(TAG, "Updating location...");
		LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
	}
	
	/**
	 * Saves a Location.
	 *
	 * @param location the location to be saved
	 */
	public void save(tcc.wa.model.Location location) {
		Log.i(TAG, "Saving location...");
		locationDAO.saveLocation(location);
	}
	
	/**
	 * Finds the last Location.
	 *
	 * @return the last saved Location
	 */
	public tcc.wa.model.Location findLast() {
		return locationDAO.findLastLocation();
	}
	
	/**
	 * Gets the Location from latitude and longitude values.
	 *
	 * @param latitude the latitude
	 * @param longitude the longitude
	 * @return a Location
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public tcc.wa.model.Location getLocationFrom(double latitude, double longitude) throws IOException {
		Geocoder geocoder = new Geocoder(context);
		Address address = null;
		List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 10);
		if (addresses.size() > 0) {
			address = addresses.get(0);
		}
		return address != null ? new tcc.wa.model.Location(address.getLocality(), address.getAdminArea(), null, address.getCountryName(), new GeographicCoordinate(address.getLatitude(), address.getLongitude())) : null;
	}
}
